<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="show" round
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:60%;">
            <view class="popup-content">
                <view class="popup-main">
                    <view>
                        <view style="display: flex; justify-content: space-between;">
                            <view class="popupTitle"> {{ title }}</view>
                            <van-icon name="cross" color="#FFFFFF" size="15" @click="closePopup" />
                        </view>

                        <view class="tabsBox">
                            <view class="popup_item" v-for="(item, index) in popupData" :key="index"
                                :class="{ active: curS === index }" @click="onClickCoupon(index, $event, item)">{{
                                item.text }}
                                <span v-if="index === 0">({{ myCouponList.length }})</span> <span v-if="index === 1">({{
                                    outOfDateCouponsList.length }})</span>
                            </view>
                        </view>
                    </view>
                    <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false">
                        <template v-if="curS === 0">
                            <view class="coupon-tips" v-if="myCouponList.length > 0">
                                已选1张优惠券，共可抵扣￥{{selectedCoupon && selectedCoupon.money ? Number(selectedCoupon.money).toFixed(2):'0.00'}}
                                <!-- 已选择推荐优惠，共抵扣￥20（您已选中抵扣￥10优惠券，共抵扣￥10）已选择推荐优惠，共抵扣￥20 -->
                            </view>
                            <view class="mycoupon_box">
                                <template v-if="myCouponList.length > 0">
                                    <!-- <van-checkbox-group ref="checkboxGroup" :max="1" :value="checked" :checked="checked"
                                        @change="handleCheck"> -->
                                    <radio-group @change="radioChange">

                                        <view class="myCoupon listItem" v-for="(item, index) in myCouponList"
                                            :key="item.id" :id="item.id">
                                            <view class="listItemLeft">
                                                <view class="itemLeft">
                                                    <view class="top">
                                                        <span>￥</span>{{ item.money }}
                                                        <!-- ￥{{ item.faceValue }} -->
                                                    </view>
                                                    <view class="item_bottom" v-if="Number(item.minPrice)>0">{{ item.limitations }}</view>
                                                </view>
                                                <view class="itemRight">
                                                    <view class="top couponName">{{ item.name }}</view>
                                                    <view class="middle term">{{ Number(item.status) ==0 ? '全部商品都可用' :
                                                        (Number(item.status) ==1 ? '限指定商品可用' :'限指定分类商品可用') }}</view>
                                                    <view class="item_bottom deadline">{{ item.deadline }}</view>
                                                </view>
                                            </view>
                                            <radio color="#FF6203" :value="item.id" :checked="item.isChecked" />
                                            <!-- <van-checkbox v-model="item.isChecked" shape="round"
                                                @click.stop="onChange('单选', item)"
                                                :disabled="item.isXiajia === true && item.isChecked === false ? true : false"
                                                use-icon-slot>
                                                <image
                                                    :src="(select && (item.isXiajia || item.isShouQing)) ? disabledIcon : (item.isChecked ? activeIcon : inactiveIcon)"
                                                    @click.stop="onChange('单选', item)" slot="icon"
                                                    class="checked-img" />
                                            </van-checkbox> -->
                                        </view>
                                    </radio-group>
                                    <!-- </van-checkbox-group> -->
                                </template>
                                <template v-if="myCouponList.length === 0">
                                    <van-empty class="custom-image"
                                        image="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCoupons.png"
                                        description="暂无可用优惠券" />
                                </template>
                            </view>
                        </template>
                        <template v-if="curS === 1">
                            <view class="mycoupon_box">
                                <template v-if="outOfDateCouponsList.length > 0">
                                    <view class="myCoupon listItem" v-for="(item, index) in outOfDateCouponsList"
                                        :key="index" :id="item.key">
                                        <view class="listItemLeft">
                                            <view class="itemLeft">
                                                <view class="shixiao">
                                                    <span>￥</span>{{ item.money }}
                                                    <!-- ￥{{ item.faceValue }} -->
                                                </view>
                                                <view class="item_bottom" v-if="Number(item.minPrice)>0">{{ item.limitations }}</view>
                                            </view>
                                            <view class="itemRight">
                                                <view class="top couponName">{{ item.name? item.name : '优惠券'}}</view>
                                                <view class="middle term">{{ Number(item.status) ==0  ? '全部商品都可用' : (Number(item.status) ==1 ? '限指定商品可用' :'限制定分类商品可用') }}</view>
                                                <view class="item_bottom outDate">{{ item.deadline }}</view>
                                            </view>
                                        </view>
                                        <view class="outOfDate">{{item.currentStatus}}</view>
                                    </view>
                                </template>
                                <template v-else>
                                    <van-empty class="custom-image"
                                        image="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCoupons.png"
                                        description="暂无过期优惠券" />
                                </template>
                            </view>
                        </template>
                    </scroll-view>

                    <van-toast id="van-toast" />
                </view>
                <view class="btn-area">
                    <van-button type="primary" class="" @click="onClickbutton">确定</van-button>
                </view>
            </view>
        </van-popup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'

export default {
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        roleName: {
            type: String,
            default: () => ''
        },
        popupBiaoshi: {
            type: Number,
            default: () => 0
        },
        ebStoreCouponResponse:{
            type:Object,
            default:()=>{}
        },
        defaultBestCoupon:{
            type:Object,
            default:()=>{}
        }
    },
    data () {
        return {
            curS: 0,
            curSName: '',
            date: '',

            title: '我的优惠券',
            option: {},
            url: '',
            stepperValue: 1,
            popupData: [
                {
                    key: 0,
                    text: '可用优惠券'

                },
                {
                    key: 1,
                    text: '不可用优惠券'

                }
            ],
            myCouponList: [
                {
                    key: 1,
                    money: 20,
                    isLimited:true,
                    limitations: '满69可用',
                    couponName: '单商品专享券',
                    term: '限指定商品可用',
                    type:'1',
                    deadline: '距失效剩2天3小时',
                    "createTime": "2025-03-07T07:41:24.381Z",
                    "updateTime": "2025-03-07T07:41:24.381Z",
                    "startTime": "2025-03-07T07:41:24.381Z",
                    "endTime": "2025-03-07T07:41:24.381Z",
                    "useTime": "2025-03-07T07:41:24.381Z",
                },
                {
                    key: 2,
                    money: 10,
                    isLimited:true,
                    limitations: '满45可用',
                    couponName: '单商品专享券',
                    term: '限指定商品可用',
                    type:'1',
                    deadline: '距失效剩2天3小时',
                    "createTime": "2025-03-07T07:41:24.381Z",
                    "updateTime": "2025-03-07T07:41:24.381Z",
                    "startTime": "2025-03-07T07:41:24.381Z",
                    "endTime": "2025-03-07T07:41:24.381Z",
                    "useTime": "2025-03-07T07:41:24.381Z",

                }
            ],
            // 过期优惠券列表
            outOfDateCouponsList: [],
            checked: [],
            checkAll: false, // 标记是否全选
            selectedRowKeys: [], // 已选择的数据的id
            selectedRows: [], // 已选择的数据
            inactiveIcon:
          'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
            activeIcon:
            'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',
            disabledIcon: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/disabledIcon.png',

            popupHeight: '300',
            // 选择的优惠券数据
            selectedCoupon:{},
            scrollHeight: 400, // 初始高度，将在mounted中动态计算
            scrollTop: 0,
            isChange:false
        }
    },

    computed: {
    },

    watch: {
        // 修改监听器处理传入的优惠券数据
        ebStoreCouponResponse: {
            immediate: true,
            handler(newVal) {
                console.log(newVal.availableCouponList,'可用优惠券（状态为1）',newVal.notavailableCouponList,'不可用优惠券（状态为0）')
                if (newVal) {
                    // 可用优惠券（状态为1）
                    this.myCouponList = (newVal.availableCouponList || []).map(item => ({
                        ...item,
                        isChecked: false,
                        // faceValue: item.discountAmount, // 根据实际字段调整
                        limitations: `满${item.minPrice}可用`,
                        deadline: this.formatDeadline(item.endTime) // 添加时间格式化方法
                    }))

                    // 不可用优惠券（状态为0）
                    this.outOfDateCouponsList = (newVal.notAvailableCouponList || []).map(item => ({
                        ...item,
                        // faceValue: item.discountAmount,
                        limitations: `满${item.minPrice}可用`,
                        currentStatus: this.formatCouponStatus(item.endTime), //不可用优惠券 当前的状态  已过期 或者不可用
                        deadline: this.formatDateRange(item.startTime, item.endTime) // 新增时间范围格式化
                    }))
                    this.selectedCoupon = this.defaultBestCoupon
                    this.isChange = false // 新增：父组件传入数据时重置修改状态
                    this.setDefaultChecked() // 监听优惠券数据变化时，设置默认选中优惠券
                }
            }
        },
        show: {
            immediate: true,
            handler(newVal) {
                if (newVal) {  // 当弹窗被父组件打开时
                    this.isChange = false  // 重置修改状态
                    // this.setDefaultChecked()  // 同步更新选中状态
                }
            }
        }
        // 新增默认优惠券监听  父组件传来的最优优惠券 在这里默认选中
        // defaultBestCoupon: {
        //     immediate: true,
        //     handler(newVal,oldVal) {
        //         // if (newVal && newVal.id) {
        //         //     console.log(newVal,newVal.id,'默认优惠券')
        //         //     this.selectedCoupon = {...newVal}
        //         // }
        //         if (newVal?.id && (!oldVal || newVal.id !== oldVal.id)) {
        //             console.log('初始化默认优惠券', newVal)
        //             this.selectedCoupon = { ...newVal }
        //         }
        //     }
        // }
    },
    onLoad () {},
    onReady () {

        this.calculateScrollHeight();
        uni.onWindowResize(() => {
            this.calculateScrollHeight();
        });
    },

    methods: {
        // 可用 或已过期优惠券
        onClickCoupon (val, e, item) {
            console.log(val, e, item, '优惠券')
            this.curS = val
            this.curSName = item.text
            console.log(this.outOfDateCouponsList, '过期优惠券')
        },

        // 关闭弹窗
        closePopup () {
            this.$emit('closeCoupon')
        },
        // 确定
        onClickbutton () {
            this.closePopup()
            
            this.$emit('submitCoupon', this.selectedCoupon,this.isChange)
        },
        setDefaultChecked() {
            if (this.defaultBestCoupon?.id) {
                this.$nextTick(() => {
                    const targetIndex = this.myCouponList.findIndex(
                        item => item.id === this.defaultBestCoupon.id
                    )
                    if (targetIndex > -1) {
                        this.myCouponList = this.myCouponList.map((item, index) => ({
                            ...item,
                            isChecked: index === targetIndex
                        }))
                    }
                })
            }
        },

        // 新增高度计算方法
        calculateScrollHeight() {
            const query = uni.createSelectorQuery().in(this);
            query.select('.popup-main').boundingClientRect(data => {
                if (data) {
                    const systemInfo = uni.getSystemInfoSync();
                    const statusBarHeight = systemInfo.statusBarHeight || 20;
                    const bottomSafeArea = systemInfo.screenHeight - systemInfo.safeArea.bottom;
                    this.scrollHeight = data.height - 160 - statusBarHeight - bottomSafeArea;
                }
            }).exec();
        },

        // 新增滚动到底部回调
        onScrollLower() {
            this.scrollTop = this.scrollTop === 0 ? 1 : 0;
        },
        // 时间格式化方法
        formatDeadline(endTime) {
            if(!endTime) return '有效期未知'
            const now = new Date();
            const endDate = new Date(endTime);
            let timeDiff = endDate - now;
            if(timeDiff < 0) return '已过期'
            // 计算剩余天数
            const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            timeDiff -= days * (1000 * 60 * 60 * 24);
            const hours = Math.floor(timeDiff / (1000 * 60 * 60));
            timeDiff -= hours * (1000 * 60 * 60);
            const minutes = Math.floor(timeDiff / (1000 * 60));

            // let result = '距失效剩'
            let result = ''
            let text = '后过期'
            if(days >0){
                result += `${days}天`
            }
            if(hours > 0) result += `${hours}小时`
            if(minutes >0) result += `${minutes}分钟`

            //处理当天过期的情况
            if(days === 0 && hours === 0 && minutes === 0 ){
                result = '已过期'
            }
            return result+text
        },
        // 新增时间范围格式化方法
        formatDateRange(startTime, endTime) {
            if (!startTime || !endTime) return '有效期未知'
            let result = ''
            const now = new Date();
            const start = new Date(startTime)
            const end = new Date(endTime)
            let timeDiff1 = end - now;
            const endYear = end.getFullYear()
            const endMonth = (end.getMonth() + 1).toString().padStart(2, '0')
            const endDay = end.getDate().toString().padStart(2, '0')
            return `${endYear}.${endMonth}.${endDay} 23:59到期`
            // return `${start.getFullYear()}-${(start.getMonth() + 1).toString().padStart(2, '0')}-${start.getDate().toString().padStart(2, '0')} 至 ${end.getFullYear()}-${(end.getMonth() + 1).toString().padStart(2, '0')}-${end.getDate().toString().padStart(2, '0')}`
        },
        // 判定优惠券的状态   已过期  或不可用
        formatCouponStatus (endTime) {
            if(!endTime) return '不可用'
            const now = new Date()
            const end = new Date(endTime)
            const timeDiff2 = end - now
            return timeDiff2 < 0 ? '已过期' : '不可用'
        },
        // // 确定排序
        // paixuClick () {
        //     this.$emit('closeCoupon')
        // },



        // 重置
        onClickReplay () {},

        // 确定    分类+价格区间
        onClickCart () {
            // this.$emit('onClickCart')
            if (this.curWeight < 0) {
                Toast('请选择重量')
            }
            Toast('加入购物车成功')
            // Toast('res.msg')
        },

        // 单选
        // 单选框
        radioChange (e) {
            console.log('radio发生change事件，携带value值为：', e.detail.value)
            this.isChange = true

            this.myCouponList.forEach((item, index) => {
                console.log(item,index, 'index', typeof (index), typeof (e.detail.value), Number(item.id) === Number(e.detail.value))
                item.isChecked = Number(item.id) === Number(e.detail.value)
                if (item.isChecked === true) {
                	this.selectedCoupon = item
                }
            })
        },

        // 复选框
        onChange (i, item) {
            console.log(i, 'i', item)

            item.isChecked = !item.isChecked
            if (item.isChecked === true) {
                this.selectedRowKeys.push(item.Id)
                this.selectedRows.push(item)
            } else {
                const index = this.selectedRowKeys.indexOf(item.Id)
                console.log(index, 'indesR')
                this.selectedRowKeys.splice(index, 1)
                this.selectedRows.splice(index, 1)
            }
        },
        // 标记  选择框   复选框
        handleCheck (item, e) {
            console.log(item, e, '单选----')
            this.checkAll = this.checked.length === this.myCouponList.length
            item.isChecked = e.detail
            if (item.isChecked === true) {
                this.selectedRowKeys.push(item.Id)
                this.selectedRows.push(item)
            } else {
                const index = this.selectedRowKeys.indexOf(item.Id)
                console.log(index, 'indesR')
                this.selectedRowKeys.splice(index, 1)
                this.selectedRows.slice(index, 1)
            }
        },

    }

}
</script>
<style lang="scss" scoped>
// 最外层
.content {
    // display: flex;
    // flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}
// 滚动
.scroll-content {
    flex: 1;
    height:1px;
}
// 提示框
.popup-content {
    display: flex;
	flex-direction: column;
	box-sizing: border-box;
    padding: 24px;
    border-radius: 16px;
    overflow: hidden;
    // height:100vh;
    height: 100%;

    .popup-main {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        height: calc(100% - 106rpx);
    }

    .popupTitle {
        font-size: 20px;
        text-align: left;
        color: #111111;
        line-height: 20px;
    }

    // 商品排序
    .tabsBox {
        padding-top: 21px;
        padding-bottom: 21px;
        display: flex;
        align-items: center;
        .popup_item {
            // font-weight: bold;
            font-size: 14px;
            text-align: left;
            color: #111111;
            line-height: 14px;
            margin-right: 22px;

            &.active {
                font-weight: bolder;
                // color: #FF6203;
            }
        }

        .popup_item:last-child {
            margin-right: 0px;
        }
    }
    .coupon-tips{
        width: 100%;
        color: #888888;
        font-size: 11px;
        text-align: left;
    }
    // 我的优惠券盒子
    .mycoupon_box{
        margin-top: 15px;
        // padding-bottom:75px;
        padding-bottom: 0; /* 移除底部留白 */
    }

    // 优惠券列表
    .listItem {
        // height: 32px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        text-align: left;
        padding:34rpx 24rpx;
        border: 1px solid #D4D4D4;
        margin-bottom: 12px;
        // background-color: paleturquoise;
        height: 174rpx;

        .listItemLeft {
            // width: 85%;
            width:calc(100% - 156rpx);
            display: flex;
            align-items: center;

            .itemLeft{
                display: flex;
                flex-direction: column;
                text-align: center;
                width: 30%;
                // min-width:fit-content ;

                .top{
                    // font-size: 0;
                    // min-width:fit-content ;
                    // span{
                        font-size: 64rpx;
                        line-height: 1;
                        color: #FF6203;
                        width: 100%;
                        height: 64rpx;
                    // }
                    span{
                        font-family: 'Courier New', Courier, monospace;
                    }
                }
                // 优惠券失效的面值样式
                .shixiao{
                    color:#B3B3B3 ;
                    font-size: 64rpx;
                    line-height: 1;
                    width: 100%;
                    height: 64rpx;
                }
                .item_bottom{
                    margin-top: 10px;
                    font-size: 26rpx;
                    line-height: 26rpx;
                    color: #111111;
                    width: 100%;
                }
            }
            .itemRight{

                display: flex;
                flex-direction: column;
                text-align: left;
                align-items: center;
                margin-left: 48rpx;
                // position: relative;
                // 优惠券名称
                .couponName{
                    // position: absolute;
                    // top: 0px;
                    width: 100%;
                    text-align: left;
                    font-size: 28rpx;
                    color: #111111;
                    // line-height: 28rpx;
                }
                // 限定商品使用
                .term{
                    // position: absolute;
                    // top: 5%;
                    width: 100%;
                    text-align: left;
                    font-size: 26rpx;
                    color: #888888;
                    line-height: 26rpx;
                    margin-top: 14rpx;
                }
                // 距离失效剩余的时间
                .deadline{
                    width: 100%;
                    font-size: 24rpx;
                    text-align: left;
                    color: #FF6203 ;
                    // line-height: 24rpx;
                    margin-top: 14rpx;
                    // position: absolute;
                }
                // 过期  失效
                .outDate{
                  width: 100%;
                  font-size: 24rpx;
                  text-align: left;
                  color: #B3B3B3;
                //   line-height: 26rpx;
                  margin-top: 14rpx;
                }
            }
        }
        // 复选框的 圆圈
        .checked-img {
            height: 16px;
            width: 16px;
        }
        // 已过期按钮
        .outOfDate{
            border-radius:12px;
            background: #ffffff;
            font-weight: 500;
            font-size: 26rpx;
            line-height: 1;
            text-align: center;
            color: #888888;
            padding: 10rpx 26rpx;
            border: 2rpx solid #D4D4D4;
        }

        .iconDiv {
            .icon {
                width: 12px;
                height: 12px;
            }
        }
    }

    .listItem:last-child {
        margin-bottom: 0px;
    }

    // 加入购物车按钮
    .goodsAction {
        margin-top: 22px;
        width: calc(100% - 48px);
        text-align: center;
        height: 84px;
    }

    .button {
        width: 100%;
        font-size: 32rpx;
        color: #ffffff;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 50rpx;
        border-style: initial !important;
        padding: 0 !important;
        background: #FF6203 !important;
    }
}

::v-deep .van-cell {
    border: 1px solid #888888;
    // background: #FF6203;
}
::v-deep .van-cell--hover .hover-class{
    border: 1px solid #888888;
}

::v-deep .van-empty {
    border-radius: 12px;
    padding: 0px !important;
}

::v-deep .van-empty__image{
    width: 105px !important;
    height: 88px !important;
    text-align: center;
}
::v-deep .van-button--primary {
  width: 100%;
  height: 86rpx;
  border-radius: 50rpx;
  background: #ff6203;
  margin-top: 32rpx;
  font-size: 28rpx;
}

.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}
</style>
